import time

import requests
import re
# douyin.py 顶部，加在最前面
import os, sys
# from .browser import douyin_browser
import requests
from playwright.sync_api import sync_playwright
from typing import Dict, List, Tuple, Optional
from playwright.sync_api import sync_playwright, Route, Request
from playwright.sync_api import Page, Response
from playwright.sync_api import sync_playwright
# from playwright_stealth import stealth_sync


from playwright.sync_api import sync_playwright
from urllib.parse import urlencode


def get_url(s):
    s = s.split('https://')[1]
    s = 'https://' + s

    s = requests.get(s).url

    return s


def get_id(s):
    s = s.split('video/')
    s = s[1].split('?')
    s = s[0]

    return s


def _is_h265(br_item: Dict) -> bool:
    # 抖音里 is_h265==1 基本就是 H.265/HEVC；is_bytevc1==1 是 ByteVC1（抖音自家编解码）
    return bool(br_item.get("is_h265"))


def _codec_name(br_item: Dict) -> str:
    if br_item.get("is_h265"):
        return "H.265/HEVC"
    if br_item.get("is_bytevc1"):
        return "ByteVC1"
    return "H.264/AVC"


def list_candidates(aweme_detail: Dict) -> List[Dict]:
    """从 aweme_detail 中取出所有清晰度候选项，补充常用字段以便排序与展示"""
    video = aweme_detail.get("aweme_detail", aweme_detail).get("video", {})
    br_list = video.get("bit_rate") or []
    out = []
    for br in br_list:
        pa = br.get("play_addr", {})
        urls = pa.get("url_list") or []
        if not urls:
            continue
        out.append({
            "height": int(pa.get("height") or 0),
            "width": int(pa.get("width") or 0),
            "fps": int(br.get("FPS") or 0),
            "bitrate_kbps": int(br.get("bit_rate") or 0) // 1000 if br.get("bit_rate") else 0,
            "gear_name": br.get("gear_name") or "",
            "quality_type": br.get("quality_type"),
            "hdr": bool(br.get("HDR_bit")),
            "codec": _codec_name(br),
            "is_h265": _is_h265(br),
            "url_list": urls,
            "url": urls[0],  # 默认给第一个
        })
    # 补充：有些视频只给了 play_addr_h264 或 play_addr_265，可作为“备胎”
    for key, codec_label in [("play_addr_h264", "H.264/AVC"), ("play_addr_265", "H.265/HEVC")]:
        pa = video.get(key) or {}
        urls = pa.get("url_list") or []
        if urls:
            out.append({
                "height": int(pa.get("height") or 0),
                "width": int(pa.get("width") or 0),
                "fps": 30,  # 常见默认
                "bitrate_kbps": int((video.get("meta") or "").isdigit() and video["meta"]) or 0,
                "gear_name": key,
                "quality_type": None,
                "hdr": False,
                "codec": codec_label,
                "is_h265": (key == "play_addr_265"),
                "url_list": urls,
                "url": urls[0],
            })
    return out


# 挑选最佳画质
def pick_best_url(
        aweme_detail: Dict,
        prefer_h264: bool = True
) -> Tuple[Optional[Dict], List[Dict]]:
    """
    返回 (best_item, all_items)。
    规则（可按需要调整）：
      1) 分辨率高者优先（height 2160 > 1440 > 1080 > 720 > 540…）
      2) 同分辨率：FPS 高者优先
      3) 同分辨率 & 同 FPS：码率高者优先
      4) 同上都相同：按编码偏好（默认优先 H.264，其次 ByteVC1/H.265）
    """
    items = list_candidates(aweme_detail)
    if not items:
        return None, []

    def codec_rank(item):
        # 偏好顺序：H.264(0) 最优 → ByteVC1(1) → H.265(2)（你也可以改成相反）
        if prefer_h264:
            return 0 if item["codec"].startswith("H.264") else (1 if "ByteVC1" in item["codec"] else 2)
        else:
            # 若想优先 H.265，把这段改成 H.265 最小排名
            return 0 if item["codec"].startswith("H.265") else (1 if "ByteVC1" in item["codec"] else 2)

    # 排序：分辨率↓, FPS↓, 码率↓, 编码偏好
    items_sorted = sorted(
        items,
        key=lambda x: (
            x["height"],
            x["fps"],
            x["bitrate_kbps"],
            -codec_rank(x)  # 偏好越小越好，所以取负号让它也降序
        ),
        reverse=True
    )
    return items_sorted[0], items_sorted


# 取id


def give(data):
    re = {"ok": True,
          "videos": [
              # {
              # "id": "1", "title": "海边日出", "author": "用户A",
              # "duration": "15s", "publish_time": "2025-09-01",
              # "cover_url": "/static/picture/demo_cover.jpg",
              # "page_url": "https://www.douyin.com/video/xxxx",
              # "play_url": "https://www.douyin.com/video/xxxx/play",
              # "download_url": "https://example.com/download/xxxx"
              # }
          ]}
    best, all_items = pick_best_url(data, prefer_h264=True)
    # data = data
    aweme = data.get("aweme_detail", {})

    if not best:
        print("没有找到可用的视频直链。")
    else:
        print("最高画质（自动挑选）:")
        print(f"  分辨率: {best['width']}x{best['height']}, FPS: {best['fps']}, 码率: {best['bitrate_kbps']} kbps")
        print(f"  编码: {best['codec']}, HDR: {best['hdr']}, 源: {best['gear_name']}")
        print(f"  直链: {best['url']}\n")

        # print("所有可用清晰度候选：")
        for i, it in enumerate(all_items, 1):
            if it['hdr']:
                re['videos'].append({'id': str(i),
                                     'title': f"{it['width']}x{it['height']}",
                                     'author': f"{it['fps']}fps",
                                     'duration': f"{it['bitrate_kbps']} kbps",
                                     'publish_time': f"{it['codec']} | {it['gear_name']}",
                                     'play_url': f"{it['url']}",
                                     'download_url': f"{it['url']}",
                                     'url': f"{it['url']}",
                                     'cover_url': '',
                                     'hdr': f"{it['hdr']}",
                                     'codec': f"{it['codec']}"
                                     })

            if not it['hdr']:
                re['videos'].append({'id': str(i),
                                     'title': f"{it['width']}x{it['height']}",
                                     'author': f"{it['fps']}fps",
                                     'duration': f"{it['bitrate_kbps']} kbps",
                                     'publish_time': f"{it['codec']} | {it['gear_name']}",
                                     'play_url': f"{it['url']}",
                                     'download_url': f"{it['url']}",
                                     'url': f"{it['url']}",
                                     'cover_url': '',
                                     'hdr': f"{it['hdr']}",
                                     'codec': f"{it['codec']}"
                                     })
                return re


def main0(s, douyin_browser):
    global jn
    url = get_url(s)
    print(url)

    id = get_id(url)
    print(id)

    for i in range(10):
        # page = douyin_browser.get_page()
        try:

            jn = douyin_browser.fetch_detail(id)

            give(jn)
        except Exception as e:
            print(e)

    return give(jn)


def main(s,douyin_browser):
    url = get_url(s)
    print(url)

    id = get_id(url)
    print(id)

    jn = douyin_browser.fetch_detail(id)

    return give(jn)



if __name__ == '__main__':
    from model.全局page import douyin_browser

    s = '1.25 复制打开抖音，看看【阿里北杯的作品】就这样偶遇蔡徐坤了…. # 蔡徐坤 # jasmi... https://v.douyin.com/zQuys-GAXrw/ y@g.oD 11/02 foq:/ '
    main0(s, douyin_browser)
